<template>
    <n-drawer :show="active" :width="width" :mask-closable="false" @update:show="(flag:boolean) => (active = flag)">
        <n-drawer-content :native-scrollbar="false" title="编辑" closable>
            <n-form :model="model" :rules="rules" ref="formRef">
                <n-grid :cols="24" :x-gap="24">
                    <n-form-item-gi :span="16" label="模板名称" path="name">
                        <n-input placeholder="请填写优惠券模板名称" v-model:value="model.name" maxlength="64" show-count clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="8" label="模板代码" path="code">
                        <n-input placeholder="请填写优惠券模板代码" v-model:value="model.code" maxlength="32" show-count clearable :disabled="model.id != ''" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="24" label="模板简介" path="memo">
                        <n-input placeholder="请填写优惠券模板简介" v-model:value="model.memo" maxlength="256" show-count clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="24" label="使用说明" path="desc">
                        <n-input placeholder="请填写优惠券模板简介" v-model:value="model.desc" type="textarea" maxlength="1024" show-count clearable />
                    </n-form-item-gi>

                    <n-form-item-gi :span="6" label="优惠方式" path="type">
                        <n-radio-group v-model:value="model.type" name="radioType">
                            <n-radio-button :value="1">金额</n-radio-button>
                            <n-radio-button :value="2">比例</n-radio-button>
                        </n-radio-group>
                    </n-form-item-gi>
                    <n-form-item-gi :span="6" label="最低订单金额" path="min">
                        <DecimalInput :border="true" :precision="2" :width="100" suffix="元" :min="0" v-model:base="model.min" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="12" label="优惠金额，按照金额减免" path="cash" v-if="model.type === 1">
                        <DecimalInput :border="true" :precision="2" :width="100" suffix="元" :min="0" v-model:base="model.cash" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="6" label="优惠折扣，按照比例抵扣" path="dis" v-if="model.type === 2">
                        <DecimalInput :border="true" :precision="1" :width="100" suffix="%" :min="0" :max="100" v-model:base="model.dis" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="6" label="最大抵扣金额" path="max" v-if="model.type === 2">
                        <DecimalInput :border="true" :precision="2" :width="100" suffix="元" :min="0" v-model:base="model.max" />
                    </n-form-item-gi>

                    <n-form-item-gi :span="4" label="有效时长" path="validity.fixed">
                        <n-switch v-model:value="model.validity.fixed" :round="false">
                            <template #checked>日期</template>
                            <template #unchecked>天数</template>
                        </n-switch>
                    </n-form-item-gi>
                    <n-form-item-gi :span="8" label="生效日期，在此日期范围内可用" v-if="model.validity.fixed">
                        <n-date-picker v-model:value="vDates" style="width: 250px" type="daterange" :update-value-on-close="true" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="8" label="有效天数，领取后几日内有效" path="validity.days" v-if="!model.validity.fixed">
                        <DecimalInput :border="true" :width="100" suffix="天" :min="0" v-model:base="model.validity.days" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="12" label="总计发放数量，0不限制" path="total">
                        <DecimalInput :border="true" :width="100" suffix="张" :min="0" v-model:base="model.total" />
                    </n-form-item-gi>

                    <n-form-item-gi :span="4" label="用户领取" path="uget.flag">
                        <n-switch v-model:value="model.uget.flag" :round="false">
                            <template #checked>允许</template>
                            <template #unchecked>禁止</template>
                        </n-switch>
                    </n-form-item-gi>
                    <n-form-item-gi :span="8" label="领取时间">
                        <n-date-picker v-model:value="gDates" style="width: 250px" type="daterange" :update-value-on-close="true" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="6" label="用户累计最大领取，0不限制" path="uget.max">
                        <DecimalInput :border="true" :width="100" suffix="张" :min="0" v-model:base="model.uget.max" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="6" label="用户每日最大领取，0不限制" path="uget.day">
                        <DecimalInput :border="true" :width="100" suffix="张" :min="0" v-model:base="model.uget.day" />
                    </n-form-item-gi>

                    <n-form-item-gi :span="24" label="可用区域 [不选择则表示全国区域]" path="areas">
                        <District v-model:code="model.areas" :tip="tip" :max="5000"></District>
                    </n-form-item-gi>
                </n-grid>
            </n-form>
            <template #footer>
                <n-space justify="end">
                    <n-button type="tertiary" :disabled="loading" @click="() => (active = false)">
                        <template #icon>
                            <n-icon :component="CloseRound" />
                        </template>
                        关闭
                    </n-button>
                    <n-button :disabled="loading" @click="execReset">
                        <template #icon>
                            <n-icon :component="RestoreRound" />
                        </template>
                        重置
                    </n-button>
                    <n-button type="primary" :loading="loading" @click="execSave">
                        <template #icon>
                            <n-icon :component="CheckRound" />
                        </template>
                        提交保存
                    </n-button>
                </n-space>
            </template>
        </n-drawer-content>
    </n-drawer>
</template>

<script lang="ts" setup>
import { computed, ref, onBeforeMount, watch } from 'vue'
import { CloseRound, CheckRound, RestoreRound } from '@vicons/material'

import { Http } from '@/libs'
import { useStore } from '@/store'

import DecimalInput from '@/comp/func/DecimalInput.vue'
import District from '@/comp/func/District.vue'

import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn' // 导入本地化语言
import customParseFormat from 'dayjs/plugin/customParseFormat'
dayjs.locale('zh-cn')
dayjs.extend(customParseFormat)

const store = useStore()
const width = computed(() => Math.max(store.state.browser.innerWidth * 0.6, 800))

const { $notification: notification } = window

const loading = ref(false)

const prop = defineProps({
    show: {
        type: Boolean,
        required: true,
    },
    item: {
        type: Object,
        default: {},
    },
})

const emit = defineEmits(['update:show', 'refresh'])

const active = computed({
    get: () => prop.show,
    set: val => emit('update:show', val),
})

const tip = ref<string>((prop.item.areas || []).map((x: any) => x.name).join(' '))

const vDates = ref<number[]>([dayjs().valueOf(), dayjs().add(1, 'month').valueOf()])
watch([vDates, () => vDates.value], (nv, _ov) => {
    let v = nv[0] as number[]
    model.value.validity.indate = dayjs(v[0]).format('YYYY-MM-DD')
    model.value.validity.expire = dayjs(v[1]).format('YYYY-MM-DD')
})

const gDates = ref<number[]>([dayjs().valueOf(), dayjs().add(1, 'month').valueOf()])
watch([gDates, () => gDates.value], (nv, _ov) => {
    let v = nv[0] as number[]
    model.value.uget.begin = dayjs(v[0]).format('YYYY-MM-DD')
    model.value.uget.close = dayjs(v[1]).format('YYYY-MM-DD')
})

const formRef = ref<any>(null)

const model = ref<any>({})

const rules = {
    name: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请填写模板名称',
    },
}

const execReset = () => {
    if (!prop.item.id) {
        model.value = {
            id: '',
            type: 1,
            name: '',
            code: '',
            memo: '',
            desc: '',
            cash: 0,
            dis: 0,
            max: 0,
            min: 0,
            total: 0,
            validity: {
                fixed: false,
                indate: dayjs().format('YYYY-MM-DD'),
                expire: dayjs().add(1, 'month').format('YYYY-MM-DD'),
                days: 30,
            },
            uget: {
                flag: true,
                max: 0,
                day: 0,
                begin: dayjs().format('YYYY-MM-DD'),
                close: dayjs().add(1, 'month').format('YYYY-MM-DD'),
            },
            mchs: [],
            areas: [],
        }
        return
    }
    model.value = {
        id: prop.item.id,
        type: prop.item.type,
        name: prop.item.name,
        memo: prop.item.memo,
        desc: prop.item.desc,
        cash: prop.item.cash,
        dis: prop.item.dis,
        max: prop.item.max,
        min: prop.item.min,
        validity: prop.item.validity,
        uget: prop.item.uget,
        total: prop.item.total,
        mchs: prop.item.mchs.map((x: any) => x.id),
        areas: prop.item.areas.map((x: any) => x.code),
    }
    if (prop.item.validity.indate && prop.item.validity.expire) {
        vDates.value = [dayjs(prop.item.validity.indate, 'YYYY-MM-DD').valueOf(), dayjs(prop.item.validity.expire, 'YYYY-MM-DD').valueOf()]
    }
    if (prop.item.uget.begin && prop.item.uget.close) {
        gDates.value = [dayjs(prop.item.uget.begin, 'YYYY-MM-DD').valueOf(), dayjs(prop.item.uget.close, 'YYYY-MM-DD').valueOf()]
    }
}

const execSave = (e: Event) => {
    e.preventDefault()
    formRef.value.validate((errors: any[]) => {
        if (!errors) {
            loading.value = true
            Http.post('/ops/opx/coupon/tmpl/save', model.value).then(resp => {
                if (resp.stat.err > 0) {
                    loading.value = false
                    return
                }
                emit('refresh', {})
                notification.success({
                    duration: 1500,
                    title: '操作成功',
                    content: '您已成功保存优惠券模板信息',
                })
                setTimeout(() => {
                    loading.value = false
                    emit('update:show', false)
                }, 200)
            })
        } else {
            let msgs = errors.map(err => err[0].message)
            notification.error({
                duration: 1500,
                title: '请填写完整内容',
                description: '当前表单存在以下问题，请处理后提交',
                content: msgs.join('\n'),
            })
        }
    })
}

onBeforeMount(() => {
    execReset()
})
</script>
